//
//  IANPLSimilarityService.m
//  VoiceClass
//
//  Created by caoxiaobo on 2017/12/17.
//  Copyright © 2017年 YRX. All rights reserved.
//

#import "IANPLSimilarityService.h"
#import "IATokenManager.h"
#import "AFNetworking.h"

static NSString * const NPLSimURLString = @"https://aip.baidubce.com/rpc/2.0/nlp/v2/simnet";

@implementation IANPLSimilarityService

+ (void)checkSimilarityBetweenText:(NSString *)text
                   withAnotherText:(NSString *)anotherText
                        completion:(NPLSimCompletion)completion {
    
    if (!completion) {
        return;
    }
    if (!text || !anotherText) {
        completion(0.0f);
        return;
    }
    
    if (![IAToken shareToken].access_token) {
        NSLog(@"无效的token");
        return;
    }
    
    // 去标点符号
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"，。！？"]];
    anotherText = [anotherText stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"，。！？"]];
    
    if ([text isEqualToString:anotherText]) { // 相同字符串 直接 100% 正确率了返回
        completion(1.0);
        return;
    }
    
    NSString *textGBK = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *anotherTextGBK = [anotherText stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLRequest *requestBOW = [self requestWithText1:textGBK text2:anotherTextGBK withModel:@"BOW"];
    NSURLSessionDataTask *dataTask1 = [manager dataTaskWithRequest:requestBOW completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        CGFloat bowRate = 0.0f;
        if (error || responseObject[@"error_msg"]) {
            bowRate = 0.0f;
        }
        bowRate = [responseObject[@"score"] floatValue];
        if (completion) {
            completion(bowRate);
        }
    }];
    [dataTask1 resume];
}

+ (NSMutableURLRequest *)requestWithText1:(NSString *)text1 text2:(NSString *)text2 withModel:(NSString *)model {
    NSDictionary *body = @{@"text_1" : text1 ? : @"",
                           @"text_2" : text2 ? : @"",
                           @"model"  : model ? : @"BOW" };
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:body options:kNilOptions error:nil];
    NSString *urlString = [NSString stringWithFormat:@"%@?access_token=%@", NPLSimURLString, [IAToken shareToken].access_token];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:bodyData];
    return request;
}

@end
